package com.example.memento.download.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.time.Duration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * 简单的独立下载工具，不需要 Spring Boot 环境
 * 可以直接运行: java -cp target/classes com.example.memento.download.util.SimpleDownloader
 */
public class SimpleDownloader {
    
    private static final String GITHUB_URL = "https://github.com/liuhuanyong/DomainWordsDict/archive/refs/heads/master.zip";
    private static final String TARGET_DIR = "data/res";
    
    public static void main(String[] args) {
        String url = args.length > 0 ? args[0] : GITHUB_URL;
        String targetDir = args.length > 1 ? args[1] : TARGET_DIR;
        
        System.out.println("开始下载...");
        System.out.println("URL: " + url);
        System.out.println("目标目录: " + targetDir);
        
        try {
            Path targetPath = Path.of(targetDir);
            downloadAndExtract(url, targetPath);
            System.out.println("下载并解压完成！");
            System.out.println("文件位置: " + targetPath.toAbsolutePath());
        } catch (Exception e) {
            System.err.println("下载失败: " + e.getMessage());
            e.printStackTrace();
            System.exit(1);
        }
    }
    
    private static void downloadAndExtract(String url, Path targetDir) throws IOException, InterruptedException {
        HttpClient client = HttpClient.newBuilder()
                .followRedirects(HttpClient.Redirect.ALWAYS)
                .connectTimeout(Duration.ofSeconds(20))
                .build();
        
        HttpRequest request = HttpRequest.newBuilder(URI.create(url))
                .timeout(Duration.ofMinutes(10))
                .header("Accept", "*/*")
                .GET()
                .build();
        
        HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
        
        if (response.statusCode() < 200 || response.statusCode() >= 300) {
            throw new IOException("HTTP " + response.statusCode() + " downloading: " + url);
        }
        
        // 下载到临时文件
        Path tempZip = Files.createTempFile("download-", ".zip");
        try (InputStream in = response.body()) {
            Files.copy(in, tempZip, StandardCopyOption.REPLACE_EXISTING);
        }
        
        // 解压到目标目录
        Files.createDirectories(targetDir);
        try (ZipInputStream zis = new ZipInputStream(Files.newInputStream(tempZip))) {
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                Path outPath = targetDir.resolve(entry.getName()).normalize();
                if (!outPath.startsWith(targetDir)) {
                    throw new IOException("Entry is outside the target dir: " + entry.getName());
                }
                if (entry.isDirectory()) {
                    Files.createDirectories(outPath);
                } else {
                    Files.createDirectories(outPath.getParent());
                    Files.copy(zis, outPath, StandardCopyOption.REPLACE_EXISTING);
                }
                zis.closeEntry();
            }
        }
        
        // 删除临时文件
        Files.deleteIfExists(tempZip);
    }
}

